package com.honeybee.cloud.framework.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64;

/**
 * @Description 图片base64
 * @Author DELL
 * @Create 2019-05-22
 * @Since 1.0.0
 */
@Slf4j
public class ImgUtil {

    /**
     * 对字节数组字符串进行Base64解码并生成图片
     *
     * @param imgStr - 图片二进制字节 imgFilePath-新生成的图片路径
     * @return
     */
    public static boolean base64ToImage(String imgStr, String imgFilePath) {
        if (StringUtils.isBlank(imgStr) || StringUtils.isBlank(imgFilePath)) {
            log.error("base64转图片异常,处理内容不正确", imgStr, imgFilePath);
            return false;
        }
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] b = decoder.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            log.error("base64转图片异常", e);
            return false;
        }
    }


}
